<!-- 自定义 -->
<template>
  <div class="map-exchange-bg">
    <el-card class="map-bg">
      <div id="dividerMap"></div>
      <div class="input-card">
        <div :class="active == '1' ? 'active' : ''" @click="drawCircle('1')"><div class="round"></div></div> 
        <div :class="active == '2' ? 'active' : ''" @click="drawRectangle('2')"><div class="square"></div></div>
        <div :class="active == '3' ? 'active' : ''" @click="orientation('3')">
          <div class="orientation">
            <i class="el-icon-location-outline"></i>
          </div> 
          </div>
      </div>
    </el-card>
    <div class="operate-bg">
      <el-card>
        <div slot="header" class="page-title-bg">
          <div class="page-title">
            <div class="title-icon">查询条件</div>
          </div>
        </div>
        <div class="formBody">
          <el-form :inline="true" size="small" class="form" label-width="120px">
            <el-form-item label="三级机构:" prop="institution">
              <el-select v-model="formInline.institution" placeholder="请选择" clearable  class="ibput">
                <el-option v-for="(item,index) in dividerList" :label="item.companyName" :value="item.companyCode" :key="index">
                  {{item.label}}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="行政区域:">
              <el-select v-model="formInline.region" placeholder="请选择" class="ibput">
                <el-option v-for="(item,index) in regionList" :label="item.label" :value="item.value" :key="index">
                  {{item.label}}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="应交月：">
              <el-date-picker
                v-model="formInline.datetimerange"
                type="monthrange"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="督导件和专收件:">
              <el-select v-model="formInline.RenewalServiceType" placeholder="请选择" class="ibput">
                <el-option label="督导件" value="1"></el-option>
                <el-option label="专收件" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="渠道:">
              <el-select v-model="formInline.channel" placeholder="请选择" class="ibput">
                <el-option label="个险" value="01"></el-option>
                <el-option label="银保" value="02"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="交次:">
              <el-select v-model="formInline.PayTime" placeholder="请选择" class="ibput">
                <el-option label="二次" value="2"></el-option>
                <el-option label="三次" value="3"></el-option>
                <el-option label="四次及以上" value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否考核件:">
              <el-select v-model="formInline.EvaluationPiece" placeholder="请选择" class="ibput">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <Card v-if="showCard">
        <div class="content" style="background: #E6A23C;display: flex;">
          <span style="margin: 0 16px;">总工作量：9 总保费：2万 总件数：10件 大额单：3件 高度困难件：2件</span>
        </div>
      </Card>
      <Card style="margin-top: 20px;">
        <el-table :data="tableList" max-height="320" style="width: 100%">
          <el-table-column width="110" label="投保人" prop="appntName" align="center" />
          <el-table-column width="110" label="保单号" prop="contNo" align="center" />
          <el-table-column width="110" label="渠道" prop="saleChnl" align="center" />
          <el-table-column width="110" label="交次" prop="paySize" align="center" />
          <el-table-column width="110" label="保费" prop="prem" align="center" />
          <el-table-column width="110" label="困难件分数" prop="hard" align="center" />
          <el-table-column width="110" label="督导件和专收件" prop="renewalType" align="center" />
          <el-table-column width="110" label="服务人员代码" prop="renewalCode" align="center" />
          <el-table-column width="110" label="服务人员姓名" prop="renewalName" align="center" />
          <el-table-column width="110" label="代理人代码" prop="agentCode" align="center" />
          <el-table-column width="110" label="代理人姓名" prop="agentName" align="center" />
          <el-table-column width="110" label="险类" prop="risk" align="center" />
        </el-table>
        <div style="float: right; margin: 20px 0;">
          <el-button type="primary" @click="seach" size="mini">查询</el-button>
          <el-button type="primary" @click="reset" size="mini">导出</el-button>
        </div>
    </Card>
    </div>
  </div>
</template>
<script>
import LabelsData from "../china-pp";
import { getCompanyList,getcustomRegionPolicyQuery } from '../../../api/renewalPlatformApi/index';
export default {
  name: '',
  data() {
    return {
      showCard:false,
      regionList:[
        { label:'锡山区',value:'320205' },
        { label:'惠山区',value:'320206' },
        { label:'滨湖区',value:'320211' },
        { label:'梁溪区',value:'320213' },
        { label:'江阴市',value:'320281' },
        { label:'宜兴市',value:'320282' },
      ],
      formInline:{
        datetimerange:[],
        institution:"",
        region:"",
        RenewalServiceType:"",
        channel:"",
        PayTime:"",
        EvaluationPiece:"",
      },
      dividerList:[],
      tableList:[],
      map: null,
      active:'0',
      typeFlag:false,
      marker:null,
      mouseTool:null,
      infoWindow:null,
      flagSeach:'',
    }
  },
  watch:{
    'formInline.institution':{
      handler(val,old){
        this.flagSeach = ''
      },
      deep:true
    }
  },
  created(){
    this.getList()
  },
  mounted() {
    this.mapLoad();
  },
  methods: {
    // 地图初始化
    mapLoad() {
      let disCountry = new AMap.DistrictLayer.Country({
        zIndex: 12,
        SOC: 'CHN',
        depth:1,
        styles: {
          'nation-stroke':'#ff0000',
          'coastline-stroke':'#0088ff',
          'province-stroke':'grey',
        }
      })
      this.map = new AMap.Map("dividerMap",{
        viewMode: '2D', // 默认使用 2D 模式，如果希望使用带有俯仰角的 3D 模式，请设置 viewMode: '3D'
        zoom:11, // 初始化地图层级
        center: [120.312983,31.492283], // 初始化地图中心点
        isHotspot: false,
        defaultCursor:'pointer',
      })
      this.map.addControl(new AMap.Scale());
      this.map.addControl(new AMap.ToolBar({ liteStyle: true }));
      this.mouseTool = new AMap.MouseTool(this.map)
      const _this = this;
      this.map.on('complete',function(){
        let layer = new AMap.LabelsLayer({
          // 开启标注避让，默认为开启，v1.4.15 新增属性
          collision: false,
          // 开启标注淡入动画，默认为开启，v1.4.15 新增属性
          animation: true,
        });
        for (let i = 0; i < LabelsData.length; i++) {
          let labelsMarker = new AMap.LabelMarker(LabelsData[i]);
          layer.add(labelsMarker);
        }
        _this.map.add(layer);
      })
    },
    drawCircle (flag) {
      console.log('2222222');
      this.flagSeach = '1'
      this.typeFlag = false
      this.active = flag
        this.mouseTool.circle({
          strokeColor: "#FF33FF",
          strokeOpacity: 1,
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillColor: '#1791fc',
          fillOpacity: 0.4,
          strokeStyle: 'solid',
        })
        this.clearMarker()
        this.mouseTool.on('draw', (event) =>{
          this.mouseTool.close()
          this.active = '0'
        })
    },
    drawRectangle (flag) {
      this.flagSeach = '1'
      this.typeFlag = false
      this.active = flag
      this.mouseTool.rectangle({
        strokeColor:'FF33FF',
        strokeOpacity:0.2,
        strokeWeight: 6,
        fillColor:'#1791fc',
        fillOpacity:0.4,
        strokeStyle: 'solid',
      })
      this.clearMarker()
      this.mouseTool.on('draw', (event)=> {
        this.mouseTool.close()
        this.active = '0'
      })
    },
    orientation(flag){
        this.flagSeach = '2'
        this.active = flag
        this.typeFlag = true
        console.log(this.typeFlag);
        if (!this.map) {  
          // 在这里初始化你的地图，你需要引入相关的库并设置你的地图选项  
          this.map = new AMap.Map('dividerMap', { // 假设你的地图容器 id 是 'mapContainer'  
          zoom: 16,  
          center: [116.397428, 39.90923],  
        });  
      }
      if(this.typeFlag){
        let _this = this
        let clickHandler = function(e){
          console.log(e,"e.id")
          _this.map.remove(_this.map.getAllOverlays());
          _this.marker = new AMap.Marker({
            position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat), //参数为经纬度
            // draggable: true,
            cursor: 'move',
            riseOnHover: true,
            bubble: true,
            cursor: 'pointer',
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
          })
          _this.map.add(_this.marker);
          _this.getInfo(e.lnglat.lng,e.lnglat.lat)
          _this.active = '0'
          _this.map.off('click',clickHandler)
        }
        this.map.on('click',clickHandler)
      }
    },
    getInfo(lng,lat){
      let address = ""
      let _this = this
      AMap.plugin("AMap.Geocoder",(e)=>{
        let geoCoder = new AMap.Geocoder({
          city: "010", //城市设为北京，默认：“全国”
          radius: 500, //范围，默认：500
        });
        geoCoder.getAddress([lng, lat], function(status, result) {
          //根据状态判断是否查询成功
          if (status === 'complete' && result.info === 'OK') {
              //地理位置信息
              address = result.regeocode.formattedAddress;
              _this.showInfoWindow(address,[lng, lat])
          } else {
              console.log("查询失败！");
          }
        })
      })
    },
    showInfoWindow(address, lnglat){
      var title = '',
      content = [];
      content.push(`地址：${address}`);
      content.push(`经纬度：${lnglat}`);
      this.infoWindow = new AMap.InfoWindow({
        isCustom: true,  //使用自定义窗体
        content: this.createInfoWindow(title, content.join("<br/>")),
        offset: new AMap.Pixel(0, 0),
      });
      this.infoWindow.open(this.map, lnglat);
    },
    //构建自定义信息窗体
    createInfoWindow(title, content) {
      var info = document.createElement("div");
      info.className = "custom-info input-card content-window-card";

      //可以通过下面的方式修改自定义窗体的宽高
      info.style.width = "400px";
      // 定义顶部标题
      var top = document.createElement("div");
      var titleD = document.createElement("div");
      // var closeX = document.createElement("img");
      top.className = "info-top";
      titleD.innerHTML = title;
      top.appendChild(titleD);
      // top.appendChild(closeX);
      info.appendChild(top);
      // 定义中部内容
      var middle = document.createElement("div");
      middle.className = "info-middle";
      middle.style.backgroundColor = 'white';
      middle.style.padding = '10px';
      middle.innerHTML = content;
      info.appendChild(middle);
      return info;
    },
    closeInfoWindow() {
      this.infoWindow.clearInfoWindow();
    },
    clearMarker() {
      if(this.marker){
        this.map.remove(this.map.getAllOverlays());
      }
    },
    getList() {
      getCompanyList({ companyType: '3',parentCode:'8601' }).then((res) => {
        if (res.code === 200) {
          res.data.forEach(item => {
            let temp = {
              companyCode: item.companyCode,
              companyName: item.companyName,
              placeCode: item.placeCode,
              isShowSon: false,
              checked: [],
              cityList: []
            }
            this.dividerList.push(temp);
          });
        }
      }).finally(() => {})
    },
    seach(){
      this.getDatalist()
    },
    getDatalist(){
      let obj = {
        // manageCom:,
        manageCom:(this.flagSeach == '1' || this.flagSeach == '2' ) ? 860101 : this.formInline.institution,
        areaId:this.formInline.region,
        willPayDateStart:this.formInline.datetimerange[0],
        willPayDateEnd:this.formInline.datetimerange[1],
        renewalType:this.formInline.RenewalServiceType,
        saleChnl:this.formInline.channel,
        paySize:this.formInline.PayTime,
        flag:this.formInline.EvaluationPiece,
      }
      getcustomRegionPolicyQuery(obj).then( res =>{
        if(res.code == 200){
          this.showCard = true
          if(this.flagSeach == '1'){
            let startNum = Math.floor(Math.random() * 2) + 1
            let endNum = Math.floor(Math.random() * 10) + 2
            this.tableList = res.data.value.slice(startNum,endNum)
          }else if(this.flagSeach == '2'){
            let arr = []
            arr.push(res.data.value[1])
            this.tableList = arr
          }else{
            if(this.formInline.institution){
              this.tableList = res.data.value
              this.mapLoad()
            }
          }
        }else{
          this.tableList = []
        }
      })
    },
    reset(){
      console.log('导出');
    },
    initReinsuranceMap() {
      // this.mapLoad()
      this.map = null;
      let acCode = '320200';
      this.map = new AMap.Map("dividerMap", {
        center: [120.305455901, 31.5700374519],
        zoom: 3
      });
      let polygons = [];
      //行政区划查询
      let opts = {
        subdistrict: 1,   // 返回下一级行政区
        showbiz: false  // 最后一级返回街道信息
      };
      let district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
      // 清除地图上所有覆盖物
      for (let i = 0, l = polygons.length; i < l; i++) {
        polygons[i].setMap(null);
      }
      district.setLevel('city'); // 行政区级别
      district.setExtensions('all');
      // 行政区查询：按照adcode进行查询可以保证数据返回的唯一性
      const _this = this;
      district.search(acCode, function (status, result) {
        if (status === 'complete') {
          let data = result.districtList[0];
          let bounds = data.boundaries;
          if (bounds) {
            for (let i = 0, l = bounds.length; i < l; i++) {
              let polygon = new AMap.Polygon({
                map: _this.map,
                strokeWeight: 1,
                strokeColor: '',
                fillColor: '',
                fillOpacity: 0.2,
                path: bounds[i]
              });
              polygons.push(polygon);
            }
            _this.map.setFitView();//地图自适应
            _this.mapLoad()
          }
        }
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.map-exchange-bg{
  display: flex;
  .page-title-bg{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .page-title{
      display: flex;
      align-items: center;
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #2A2A2A;
      .title-icon{
        color: #fff;
      }
    }
    .page-title-operate{
      padding-left: 10px;
    }
  }
  .formBody{
    .ibput{
      width:150px
    }
  }
  
  .map-bg{
    width: 60%;
    position: relative;
    ::v-deep.el-card__body{
      padding: 0;
    }
    #dividerMap{
      width: 100%;
      height: calc(100vh - 160px);
      position: relative;
    }
    .input-card{
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      background: #fff;
      height: 50px;
      width: 180px;
      position: absolute;
      top: 10px;
      right: 20px;
      border: 1px solid #e4e7ed;
      div{
        width:60px;
        height:50px;
        display:flex;
        align-items: center;
        justify-content: center;
        .round{
          width: 40px;
          height: 40px;
          border: 4px solid #372AE4;
          border-radius: 50%;
          background-color: #fff;
        }
        .square{
          width: 40px;
          height: 40px;
          border: 4px solid #372AE4;
        }
        .orientation{
          i{
            font-size: 40px;
            color: #372AE4;
          }
        }
      }
      .active{
        width:60px;
        height:50px;
        background:rgb(220, 223, 230);
        display:flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .operate-bg{
    width: 39%;
    margin-left: 10px;
    .divide-bg{
      .divide-upload{
        padding: 0 0 10px 10px;
        span:nth-child(1){
          color: #818181;
        }select
        span:nth-child(2){
          color: #CFCFCF;
        }
      }
      .upload-btn{
        display: inline-block;
      }
    }
  }
  ::v-deep.el-card__header {
    border: 0;
    background-color: #082AFF;
    border-radius: 10px 10px 0 0;
  }
  ::v-deep.el-card__body{
    padding: 15px;
  }
}
// .content{
//   // height: 30px;
//   background: #E6A23C;
//   // margin-bottom: 20px;
//   span{
//     line-height: 30px;
//     margin: 0 16px;
//   }
// }
</style>
